<template>
  <div ref="gridRef" class="grid" :style="gridStyle">
    <div v-for="b in bookmarks" :key="b.id" class="bm-item" :data-id="b.id" :draggable="true" @dragstart="(e)=>onNativeDragStart(e,b.id)" @dragend="onNativeDragEnd">
      <BookmarkCard :bookmark="b" @edit="(bb)=>emit('edit', bb)" />
    </div>
    <div class="no-drag"><slot /></div>
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import BookmarkCard from './BookmarkCard.vue';
import type { Bookmark } from '../../core/types/model';
import { useSettings } from '../../core/store/useSettings';
import Sortable from 'sortablejs';
import { useBookmarks } from '../../core/store/useBookmarks';

const props = defineProps<{ bookmarks: Bookmark[], groupId?: string }>();
const emit = defineEmits<{ (e:'edit', b: Bookmark): void }>();
const settings = useSettings();
const gridStyle = computed(() => ({
  gridTemplateColumns: `repeat(${settings.settings?.columns || 5}, 1fr)`
}));

const gridRef = ref<HTMLDivElement>();
let sortable: Sortable | null = null;
const bm = useBookmarks();

onMounted(() => {
  if (!gridRef.value) return;
  
  // 简单粗暴的解决方案：使用全局事件
  let draggedBookmarkId = '';
  
  sortable = Sortable.create(gridRef.value, {
    animation: 150,
    ghostClass: 'drag-ghost',
    filter: '.no-drag',
    draggable: '.bm-item',
    onStart(evt) {
      const item = evt.item as HTMLElement;
      if (item?.dataset?.id) {
        draggedBookmarkId = item.dataset.id;
        // 触发全局事件，告诉其他组件正在拖拽哪个书签
        window.dispatchEvent(new CustomEvent('bookmark-drag-start', {
          detail: { bookmarkId: item.dataset.id, sourceGroupId: props.groupId }
        }));
        // 兼容：直接设置全局变量，DockBar 在 drop 时可读取（避免监听偶发丢失）
        try { (window as any).__gce_draggingBookmarkId = item.dataset.id; } catch {}
      }
    },
    onEnd(evt) {
      // 延迟清理，确保 Dock 的 drop 先读取到 bookmarkId
      setTimeout(() => {
        window.dispatchEvent(new CustomEvent('bookmark-drag-end'));
        try { (window as any).__gce_draggingBookmarkId = ''; } catch {}
        draggedBookmarkId = '';
      }, 0);

      // 延迟执行组内排序，确保跨组拖拽优先完成
      setTimeout(() => {
        // 仅当落点仍为当前网格容器时才进行组内排序，避免拖到 Dock 时的干扰
        if (!gridRef.value || evt?.to !== gridRef.value) return;
        // 组内排序
        const ids = Array.from(gridRef.value!.querySelectorAll('.bm-item'))
          .map((el) => (el as HTMLElement).dataset.id!)
          .filter(Boolean);
        const gid = props.groupId ?? 'default';
        bm.reorderWithinGroup(gid, ids).catch((e) => {
          try { (window as any).gceToast?.(e?.message || '⚠️ 保存失败，已回滚'); } catch {}
        });
      }, 100);
    }
  });
});

function onNativeDragEnd(){
  // 清理拖拽状态
  document.body.style.userSelect = '';
}

function onNativeDragStart(e: DragEvent, id: string){
  try{
    e.dataTransfer?.setData('text/gce-bookmark-id', id);
    e.dataTransfer?.setData('text/plain', id);
    // 允许复制/移动
    if (e.dataTransfer) {
      try { e.dataTransfer.effectAllowed = 'copyMove'; } catch {}
    }
  }catch{}
  // 提升体验：拖拽时禁用文本选择
  document.body.style.userSelect = 'none';
}
</script>
<style scoped>
.grid{ display:grid; gap:8px; align-content:start; justify-content:center; }
.bm-item{ min-width:0; overflow:visible; }
.drag-ghost{ opacity:.6; }
</style>
